<template>
	<view class="page index">
		<view class="header">
			<view class="info">
				<view class="left">
					<view class="type">
						{{detail.name}}
					</view>
					<view class="status" :style="{color: `${detail.color}`, borderColor: `${detail.color}`}">
						{{detail.statusText}}
					</view>
				</view>
				<view class="code">
					审批编号：{{detail.id}}
				</view>
			</view>
			<view class="member">
				<view class="avatar">
					<image src="@/static/images/avatar.png" mode="aspectFill"></image>
				</view>
				<view class="mess">
					<view class="name">
						{{detail.startUser.nickname}}
					</view>
					<view class="depart">
						{{detail.startUser.deptName}}
					</view>
				</view>
			</view>
		</view>
		<view class="main">
			<block v-if="$share.getApprovalType()[detail.processDefinition.key].id  == 1">
				<project-implementation :businessKey="detail.businessKey"></project-implementation>
			</block>
			<block v-if="$share.getApprovalType()[detail.processDefinition.key].id  == 2">
				<project-deliver :businessKey="detail.businessKey"></project-deliver>
			</block>
			<block v-if="$share.getApprovalType()[detail.processDefinition.key].id  == 3">
				<project-pause :businessKey="detail.businessKey"></project-pause>
			</block>
			<block v-if="$share.getApprovalType()[detail.processDefinition.key].id  == 4">
				<project-repeal :businessKey="detail.businessKey"></project-repeal>
			</block>
			<block v-if="$share.getApprovalType()[detail.processDefinition.key].id  == 5">
				<project-document :businessKey="detail.businessKey"></project-document>
			</block>
			<block v-if="$share.getApprovalType()[detail.processDefinition.key].id  == 6">
				<contract-approval :businessKey="detail.businessKey"></contract-approval>
			</block>
			<block v-if="$share.getApprovalType()[detail.processDefinition.key].id  == 7">
				<contract-cancel :businessKey="detail.businessKey"></contract-cancel>
			</block>
			<block v-if="$share.getApprovalType()[detail.processDefinition.key].id  == 8">
				<payment-approval :businessKey="detail.businessKey"></payment-approval>
			</block>
			<block v-if="$share.getApprovalType()[detail.processDefinition.key].id  == 9">
				<payment-cancel :businessKey="detail.businessKey"></payment-cancel>
			</block>
		</view>
		<view class="footer">
			<button class="process" @click="process">查看审批流程</button>
			<!-- <button class="return" @click="toReturn">退回</button> -->
			<button v-if="isShow" class="pass" @click="openApproval">通过</button>
		</view>
		<!-- 是否通过申请弹出框 -->
		<uni-popup ref="approval" type="center">
			<view class="model-popup">
				<view class="top">
					<view class="title">
						审批
					</view>
					<view class="content">
						<view class="item">
							<view class="item-name">
								<span style="color: #bd3124;">*</span>审批意见
							</view>
		          <input class="input" v-model="reason" type="text" placeholder="请输入审批意见">
						</view>
						<view class="item">
							<view class="item-name">
								抄送人
							</view>
						  <input class="input" v-model="copyUser" type="text" placeholder="请选择抄送人" :disabled="true" @click="show = true">
						</view>
					</view>
				</view>
				<view class="bottom">
					<button class="cancle" @click="unPass">不通过</button>
					<button class="confire" @click="pass">通过</button>
				</view>
			</view>
		</uni-popup>
		<common-select :show="show" :list="userList" desc="暂无用户" @changePopup="changeShow" @select="select"></common-select>
	</view>
</template>

<script>
	import projectImplementation from "./components/projectImplementation.vue";
	import projectDeliver from "./components/projectDeliver.vue";
	import projectPause from "./components/projectPause.vue";
	import projectRepeal from "./components/projectRepeal.vue"
	import projectDocument from "./components/projectDocument.vue";
	import contractApproval from "./components/contractApproval.vue";
	import contractCancel from "./components/contractCancel.vue";
	import paymentApproval from "./components/paymentApproval.vue"
	import paymentCancel from "./components/paymentCancel.vue";
	import commonSelect from "@/components/commonSelect.vue";
	import {getDetailsApi, approvalPassApi, approvalRejectApi, approvalReturnApi, getProcessInstanceIdApi} from "@/api/approval_api.js";
	import {getUserListApi} from "@/api/common.js";
	export default{
		components:{
			projectImplementation,
			projectDeliver,
			commonSelect,
			projectPause,
			projectRepeal,
			projectDocument,
			contractApproval,
			contractCancel,
			paymentApproval,
			paymentCancel
		},
		data(){
			return {
				id: 0, //审批任务的processInstanceId
				detail:{},
				show: false,//多选框
				userList: [],
				copyUserIds:[], //抄送人id
				copyUser: '',//抄送人
				reason: '',
				userId: 0,//当前用户id
				runningTasks: [],//处理任务
				isShow: false,
			}
		},
		async onLoad(e) {
			this.id = e.id;
			this.isShow = e.showPass == 'true' ? true : false;
			this.userId = getApp().globalData.userInfo.id;
			await uni.showLoading({
				mask: true,
				title: ' 加载中...'
			})
			await this.getDetails();
			if(this.isShow){
				await this.getProcessInstanceId();
			}
		},
		methods:{
			//获得指定流程实例任务列表
			async getProcessInstanceId(){
				let res = await getProcessInstanceIdApi(this.id);
				let tasks = [];
				// 1.1 移除已取消的审批
				res.data.forEach((task) => {
					if (task.status !== 4) {
						tasks.push(task)
					}
				})
				// 1.2 排序，将未完成的排在前面，已完成的排在后面；
				tasks.sort((a, b) => {
					// 有已完成的情况，按照完成时间倒序
					if (a.endTime && b.endTime) {
						return b.endTime - a.endTime
					} else if (a.endTime) {
						return 1
					} else if (b.endTime) {
						return -1
						// 都是未完成，按照创建时间倒序
					} else {
						return b.createTime - a.createTime
					}
				})
				this.runningTask(tasks);
			},
			//获取需要自己审批的任务
			runningTask(tasks){
				tasks.forEach((task) => {
					if (task.children !== null) {
						loadRunningTask(task.children)
					}
					// 2.1 只有待处理才需要
					if (task.status !== 1 && task.status !== 6) {
						return
					}
					// 2.2 自己不是处理人
					if (!task.assigneeUser || task.assigneeUser.id !== this.userId) {
						return
					}
					// 2.3 添加到处理任务
					this.runningTasks.push({ ...task })

					// 2.4 处理 approve 表单
					// if (task.formId && task.formConf) {
					// 	const approveForm = {}
					// 	setConfAndFields2(approveForm, task.formConf, task.formFields, task.formVariables)
					// 	approveForms.value.push(approveForm)
					// } else {
					// 	approveForms.value.push({}) // 占位，避免为空
					// }
				})
				console.log(this.runningTasks)
			},
			//获取详情
			async getDetails(){
				let res = await getDetailsApi(this.id).catch(() => {
					uni.hideLoading();
					return Promise.reject();
				})
				this.detail = res.data;
				let statusText = '';
				let color = '';
				switch(res.data.status){
					case 1: {
						statusText = '审批中';
						color = '#F4CE98';
						break;
					}
					case 2: {
						statusText = '已通过';
						color = '#A2EF4D';
						break;
					}
					case 3: {
						statusText = '不通过';
						color = '#f56c6c';
						break;
					}
					case 4: {
						statusText = '已取消';
						color = '#C9C9C9';
						break;
					}
					case 5: {
						statusText = '已退回';
						color = '#BD3124';
						break;
					}
					case 6: {
						statusText = '委派中';
						color = '#198AFA';
						break;
					}
				}
				this.$set(this.detail, 'statusText', statusText);
				this.$set(this.detail, 'color', color);
				await uni.hideLoading();
			},
			// 是否通过申请
			changeShow(e){
				this.show = e;
			},
			// 获取用户列表
			openApproval(){
				this.$refs.approval.open();
				getUserListApi().then((res) => {
					this.userList = res.data.map((item) => {
						let value = item.id;
						let name = item.nickname;
						return {
							value,
							name
						}
					})
				})
			},
			// 选择抄送人
			select(e){
				this.copyUser = e.map((item) => item.name).join(',');
				this.copyUserIds = e.map((item) => item.value);
			},
			// 审批通过
			pass(){
				this.$refs.approval.close();
				if(this.reason == ''){
					uni.showToast({
						icon: 'none',
						title: '审批意见不能为空'
					})
					return;
				}
				uni.showLoading({
					mask: true,
					title: '加载中...'
				})
				approvalPassApi({
					id: this.runningTasks[0].id,
					reason: this.reason,
					copyUserIds: this.copyUserIds
				}).then(() => {
					uni.hideLoading();
					uni.showToast({
						icon: 'success',
						title: '审批通过'
					})
					this.getDetails();
				})
			},
			// 不通过审批
			unPass(){
				this.$refs.approval.close();
				if(this.reason == ''){
					uni.showToast({
						icon: 'none',
						title: '审批意见不能为空'
					})
					return;
				}
				approvalRejectApi({
					id: this.runningTasks[0].id,
					reason: this.reason
				}).then(() => {
					uni.hideLoading();
					uni.showToast({
						icon: 'success',
						title: '操作成功'
					})
					this.getDetails();
				})
			},
			// 退回
			toReturn(){
				uni.showModal({
					title: '退回审批',
					editable: true,
					placeholderText: '请输入退回原因',
					success(res) {
						console.log(res, '==============')
						if (res.confirm) {
							if(res.content == ''){
								uni.showToast({
									icon: 'none',
									title: '请输入退回原因'
								})
								return;
							}
							approvalReturnApi({
								id: this.runningTasks[0].id,
								reason: res.content
							})
						}
					}
				})
			},
			process(){
				uni.navigateTo({
					url: `/pages/index/approval/approvalProcess?id=${this.id}&status=${encodeURIComponent(JSON.stringify(this.detail))}`
				})
			},
		}
	}
</script>

<style lang="scss" scoped>
	@import "@/common/style/customicons.scss";
	.index{
		@include flex-c;
		.header{
			padding: 24rpx 28rpx 0;
			flex: 0 0 auto;
			.info{
				@include flex-r-between-center;
				.left{
					@include flex-r-start-center;
					.type{
						color: #000;
						font-size: 28rpx;
						padding-right: 20rpx;
					}
					.status{
						@include flex-r-center-center;
						width: 116rpx;
						height: 44rpx;
						border-radius: 6rpx;
						border: 4rpx #F4CE98 solid;
						color: #F4CE98;
						font-size: 26rpx;
					}
				}
				.code{
					color: #9A9A9A;
					font-size: 26rpx;
					width: 370rpx;
					@include essipsis;
				}
			}
			.member{
				padding: 24rpx 0 0;
				@include flex-r-start-center;
				.avatar{
					@include avatar(72);
				}
				.mess{
					padding-left: 20rpx;
					.name{
						color: #000;
						font-size: 28rpx;
						line-height: 44rpx;
					}
					.depart{
						color: #9A9A9A;
						font-size: 24rpx;
						line-height: 44rpx;
					}
				}
			}
		}
		.main{
			flex: 1 0 0;
			overflow: auto;
		}
		.footer{
			padding: 24rpx 28rpx;
			flex: 0 0 auto;
			@include flex-r-center-start;
			button{
				@include button;
				width: 48%;
				height: 54rpx;
				line-height: 54rpx;
				color: #fff;
				font-size: 26rpx;
				
			}
			.process{
				background-color: #BEBEBE;
			}
			.return{
				background-color: #DE868F;
			}
			.pass{
				background-color: #198AFA;
				margin-left: 4%;
			}
		}
		.model-popup{
			width: 600rpx;
			background-color: #fff;
			@include box;
			border-radius: 16rpx;
			.top{
				padding: 24rpx 40rpx 56rpx;
				.title{
					color: #101010;
					font-size: 36rpx;
					text-align: center;
					padding: 0 0 20rpx;
				}
				>.content{
					.item{
						display: flex;
						align-items: center;
						padding: 30rpx 0 0;
						.item-name{
							flex: 1;
							font-size: 28rpx;
							color: #101010;
							text-align: right;
							padding-right: 10rpx;
						}
						.input{
							flex: 3;
							border: 2rpx #e8e8e8 solid;
							border-radius: 6rpx;
							padding: 0 10rpx;
							height: 45rpx;
							line-height: 45rpx;
							font-size: 28rpx;
						}
					}
				}
			}
			.bottom{
				@include flex-r;
				border-top: 4rpx #F0F0F2 solid;
				button{
					@include button;
					width: 50%;
					height: 90rpx;
					line-height: 90rpx;
					font-size: 32rpx;
					background-color: #fff;
					border-radius: 0;
				}
				.cancle{
					color: #BBBBBB;
					border-right: 4rpx #F0F0F2 solid;
				}
				.confire{
					color: #4095E5;
				}
			}
		}
	}
</style>